package mn.idax.exchange.otc.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mn.idax.exchange.auth.bean.AuthInfo;
import mn.idax.exchange.auth.util.AuthInfoUtils;
import mn.idax.exchange.common.bean.ResponseData;
import mn.idax.exchange.otc.constant.RequestUrlConstant;
import mn.idax.exchange.otc.domain.OTCArbitrationJudgeRequest;
import mn.idax.exchange.otc.domain.OTCArbitrationRequest;
import mn.idax.exchange.otc.domain.OrderChangeDTO;
import mn.idax.exchange.otc.entity.*;
import mn.idax.exchange.otc.enums.CommentTypeEnum;
import mn.idax.exchange.otc.enums.DictEnum;
import mn.idax.exchange.otc.enums.OTCArbitrationEnum;
import mn.idax.exchange.otc.enums.OrderState;
import mn.idax.exchange.otc.enums.response.OTCArbitrationResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.service.OTCArbitrationService;
import mn.idax.exchange.otc.service.OTCCommentService;
import mn.idax.exchange.otc.service.OTCOrderService;
import mn.idax.exchange.otc.service.OTCSysDictionaryItemService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.util.LogUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Auther: shihaiming
 * @Date: 2018/08/15
 * @Description:
 */

@Api(value = "仲裁",tags={"仲裁"})
@RequestMapping(RequestUrlConstant.MODULE_ARBITRATION)
@RestController
public class OTCArbitrationController {

    @Autowired
    private OTCArbitrationService otcArbitrationService;
    @Autowired
    private OTCOrderService otcOrderService;
    @Autowired
    private OTCSysDictionaryItemService otcSysDictionaryItemService;

    @Autowired
    private OTCCommentService otcCommentService;
    
    
    /**
     *  创建仲裁
     * @param otcCArbitrationRequest
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "创建仲裁", notes = "(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.ARBITRATION_CREATE,method = RequestMethod.POST)
    public ResponseData create(@Valid @RequestBody OTCArbitrationRequest otcCArbitrationRequest,
                       HttpServletRequest request) throws Exception{

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        //检查申诉类型是否正确
    	boolean bool = false;
    	List<OTCSysDictionaryItem> otcSysDictionaryItemList = otcSysDictionaryItemService.listItem(DictEnum.COMPLAINT_TYPE.getCode());
    	for (int i = 0; i < otcSysDictionaryItemList.size(); i++) {
    		if (otcSysDictionaryItemList.get(i).getItemvalue().equals(otcCArbitrationRequest.getType())) {
    			bool = true;
    			break;
    		}
		}
    	if (!bool) {
    		throw new IdaxException(OTCArbitrationResponseEnum.ARBITRATION_TYPE_NOT_EXIST.getCode());
    	}
    	
        //查询订单信息，获取买卖交易人
        OTCOrder otcOrder = otcOrderService.getOrderByOrderNum(otcCArbitrationRequest.getOrdernum());
        if(otcOrder == null) {
        	throw new IdaxException(OTCArbitrationResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //订单完成 双方评价完 有一笔差评 + 广告主
        if (otcCArbitrationRequest.getType().equals(6)){
            if (!otcOrder.getOrderstate().equals(OrderState.STATE_FINISH.getCode())){
                throw new IdaxException(OTCArbitrationResponseEnum.JUDGE_AT_ORDER_UNFINISH.getCode());
            }
            List<OTCComment> commentByOrderNum = otcCommentService.getCommentByOrderNum(otcOrder.getNumber());
            if (!userId.equals(otcOrder.getAdvertiser()) || (commentByOrderNum.size() != 2
                    || commentByOrderNum.stream().noneMatch(p ->p.getCommenttype().equals(CommentTypeEnum.COMMENT_NEGATIVE.getCode())))){
                throw new IdaxException(OTCArbitrationResponseEnum.COMMENTDATE_INCORRECT.getCode());
            }

        }

        //检查订单状态
        if(!OrderState.STATE_PAID.getCode().equals(otcOrder.getOrderstate())
                && !OrderState.STATE_TORELEASED.getCode().equals(otcOrder.getOrderstate())
                && !OrderState.STATE_FINISH.getCode().equals(otcOrder.getOrderstate())
                && !OrderState.STATE_BUYER_CANCEL.getCode().equals(otcOrder.getOrderstate())
                && !OrderState.STATE_EXPIRE.getCode().equals(otcOrder.getOrderstate())) {

            throw new IdaxException(OTCArbitrationResponseEnum.CAN_NOT_APPLY_ARBITRATION.getCode());
        }
        
        OTCArbitration otcArbitration = new OTCArbitration();
        BeanUtils.copyProperties(otcCArbitrationRequest, otcArbitration);
        //id为自增字段
        otcArbitration.setId(null);
        otcArbitration.setStatus(OTCArbitrationEnum.state_apply.getCode());
        //订单id，非订单号
        otcArbitration.setOrderid(otcOrder.getId());
        otcArbitration.setType(otcCArbitrationRequest.getType());
        
        //封装更新订单的实体
        OrderChangeDTO orderChangeDTO = new OrderChangeDTO();
    	orderChangeDTO.setOrderNum(otcCArbitrationRequest.getOrdernum());
    	
        if(otcOrder.getBuyer().equals(userId)) {
        	orderChangeDTO.setOrderState(OrderState.STATE_BUYER_ARBITRATION.getCode());
        	otcArbitration.setSubstatus(OTCArbitrationEnum.sub_state_buy_apply.getCode());
        }else if(otcOrder.getSeller().equals(userId)) {
        	orderChangeDTO.setOrderState(OrderState.STATE_SELLER_ARBITRATION.getCode());
        	otcArbitration.setSubstatus(OTCArbitrationEnum.sub_state_seller_apply.getCode());
        }else {
        	throw new IdaxException(OTCArbitrationResponseEnum.NO_ORDER_TRADER.getCode());
        }
        
        Date currDate = DateUtils.getUTCNow();
        otcArbitration.setCreatetime(currDate);
        otcArbitration.setUpdatetime(currDate);
        otcArbitration.setPleaduserid(userId);
        
        //仲裁明细表
        OTCArbitrationDetail otcArbitrationDetail = new OTCArbitrationDetail();
        otcArbitrationDetail.setCreatetime(currDate);
        otcArbitrationDetail.setBuyerid(otcOrder.getBuyer());
        otcArbitrationDetail.setSellerid(otcOrder.getSeller());
        otcArbitrationDetail.setOldpleadstatus(otcArbitration.getStatus());
        otcArbitrationDetail.setOldpleadsubstatus(otcArbitration.getSubstatus());
        otcArbitrationDetail.setPleadstatus(otcArbitration.getStatus());
        otcArbitrationDetail.setPleadsubstatus(otcArbitration.getSubstatus());
    	
        //保存数据
        otcArbitrationService.add(otcArbitration, otcArbitrationDetail, orderChangeDTO,userId.equals(otcOrder.getBuyer()),otcOrder);

        return ResponseData.success();
    }

    @ApiOperation(value = "推送判定信息", notes = "(dison，开发中)")
    @RequestMapping(value = RequestUrlConstant.ARBITRATION_PUSH_JUDGE,method = RequestMethod.POST)
    public ResponseData pushJudgeInfo(@RequestBody OTCArbitrationJudgeRequest judge){
        LogUtils.info(this.getClass(),"pushJudgeInfo method start ...");
        boolean flag = this.otcArbitrationService.pushJudgeInfo(judge);
        if (!flag){
            throw new IdaxException(OTCArbitrationResponseEnum.PUSH_JUDGE_INFO_FAIL.getCode());
        }
        return ResponseData.success();
    }


    @ApiOperation(value = "查看仲裁判定详情", notes = "(dison，开发中)")
    @RequestMapping(value = RequestUrlConstant.ARBITRATION_SHOW_DETAIL,method = RequestMethod.POST)
    public ResponseData showDetail(@RequestBody OTCArbitrationJudgeRequest judge){
        String showDetail = this.otcArbitrationService.showDetail(AuthInfoUtils.getCurrent().getId(), judge);
        return ResponseData.success(showDetail);
    }

    
}
